package com.uduemc.biso.node.core.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlToBase64Util {

//	public static void main(String[] args) throws Exception {
//		String imageUrl = "https://bisostatic.35.cn/site/assets/formemail/mail1.jpg";
//		String imgageFile = "E:\\360Downloads\\mail1.jpg";
//
//		imageUrlDownload(imageUrl, imgageFile);
//	}

	public static void imageUrlDownload(String urlStr, String dir) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		File file = new File(dir);// 创建文件，dir=绝对路径+图片名称后缀
		try {
			URL url = new URL(urlStr);
			URLConnection urlConnection = url.openConnection();
			inputStream = urlConnection.getInputStream();
			outputStream = new FileOutputStream(file);
			byte[] bytes = new byte[1024];
			int n = 0;
			while ((n = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, n);
			}
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}

		}
	}
}
